package com.diary;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import com.diary.DaoMaster.DevOpenHelper;

//继承来自listView
public class LifeDiary extends ListActivity {
	// 检查密码
	private SharedPreferences textpassword = null;
	private String password = null;
	private boolean isSet = false;
	private EditText checkpass = null;
	// 检查是否第一次进入应用
	boolean isFirstIn = false;
	// 插入一条新纪录
	public static final int MENU_ITEM_INSERT = Menu.FIRST;
	// 编辑内容
	//public static final int MENU_ITEM_EDIT = Menu.FIRST + 1;
	public static final int MENU_ITEM_QUIT=Menu.FIRST+1;
	public static final int MENU_ITEM_ALLDELETE=Menu.FIRST+2;
	// private static final String[] PROJECTION =
	// new String[] { DiaryColumns._ID,
	// DiaryColumns.TITLE, DiaryColumns.CREATED };
	//
	// GreenDAO使用的变量
	private SQLiteDatabase db;

	private DaoMaster daoMaster;
	private DaoSession daoSession;
	private NoteDao noteDao;

	private Cursor cursor;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.diary_list);

		// 初始化GreenDAO
		InitDAO();

		// 初始化List
		InitList();
	}

	/*
	 * 初始化DAO
	 */
	private void InitDAO() {
		DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db",
				null);
		db = helper.getWritableDatabase();
		daoMaster = new DaoMaster(db);
		daoSession = daoMaster.newSession();
		noteDao = daoSession.getNoteDao();

	}

	/*
	 * 初始化List
	 */
	private void InitList() {
		String textColumn = NoteDao.Properties.Title.columnName;
		String dateColunm = NoteDao.Properties.Date.columnName;
		String orderBy = dateColunm + " COLLATE LOCALIZED DESC";
		cursor = db.query(noteDao.getTablename(), noteDao.getAllColumns(),
				null, null, null, null, orderBy);
		String[] from = { textColumn, dateColunm };
		int[] to = { R.id.text1, R.id.created };

		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
				R.layout.diary_row, cursor, from, to);
		setListAdapter(adapter);
	}


	// 添加选择菜单
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(Menu.NONE, MENU_ITEM_INSERT, 0, R.string.menu_insert);//添加新日记
		menu.add(Menu.NONE, MENU_ITEM_QUIT, 0, R.string.menu_quit);//退出软件
		menu.add(Menu.NONE,MENU_ITEM_ALLDELETE,0,R.string.menu_alldelete);//删除全部日记
		return true;
	}

	// 添加选择菜单的选择事件
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// 插入一条数据
		case MENU_ITEM_INSERT:
			Intent intent0 = new Intent(this, DiaryEditor.class);
			intent0.setAction(DiaryEditor.INSERT_DIARY_ACTION);
			intent0.setData(getIntent().getData());
			startActivity(intent0);
			LifeDiary.this.finish();
			cursor.requery();
			return true;
        //退出软件
		case MENU_ITEM_QUIT:
			 quit();//弹出对话框，确认是否退出软件
			return true;
        //全部删除
		case MENU_ITEM_ALLDELETE:
			deletealldiary();//弹出对话框，确认是否全部删除
            return true;
		}
		return super.onOptionsItemSelected(item);
	}
    //弹出对话框
	public void quit(){
		//通过new AlertDialog.Builder dialog对象，构造一个对话窗口
		AlertDialog.Builder dialog=new AlertDialog.Builder(LifeDiary.this);
		dialog.setTitle(R.string.remind);//设置对话框标题
		dialog.setMessage(R.string.ask);//设置对话框内容
		//设置确定按钮
		dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int i) {
				System.exit(0);//退出软件
			}
		});
		//设置取消按钮
		dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int i) {
			}
		});
		dialog.show();//显示对话框
	}
	//弹出对话框
	public void deletealldiary(){
		//通过new AlertDialog.Builder dialog对象，构造一个对话窗口
		AlertDialog.Builder dialog=new AlertDialog.Builder(LifeDiary.this);
		dialog.setTitle(R.string.remind);
		dialog.setMessage(R.string.deleteall);
		dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int i) {
				noteDao.deleteAll();//用数据库的清空功能
				Intent intent = new Intent(LifeDiary.this, LifeDiary.class);
				startActivity(intent);//重新跳转进主界面
				LifeDiary.this.finish();
			}
		});
		dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int i) {
			}
		});
		dialog.show();//展示对话框
	}

    //编辑日记
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
		String mid = Long.toString(id);
		Log.d("id", mid);
		// Intent intent = new Intent();
		// startActivity(new Intent(DiaryEditor.EDIT_DIARY_ACTION, uri));
		Intent intent = new Intent(this, DiaryEditor.class);
		intent.setAction(DiaryEditor.EDIT_DIARY_ACTION);
		Bundle bundle = new Bundle();
		bundle.putLong("id", id);
		intent.putExtras(bundle);
		Log.d("id", mid);
		startActivity(intent);
		LifeDiary.this.finish();
		cursor.requery();
	}

	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		cursor.requery();
		super.onActivityResult(requestCode, resultCode, intent);
		// renderListView();
	}
	// @SuppressWarnings("deprecation")
	// private void renderListView() {
	// Cursor cursor = managedQuery(getIntent().getData(), PROJECTION,
	// null,null, DiaryColumns.DEFAULT_SORT_ORDER);
	//
	// SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
	// R.layout.diary_row, cursor, new String[] { DiaryColumns.TITLE,
	// DiaryColumns.CREATED }, new int[] { R.id.text1,R.id.created });
	// setListAdapter(adapter);
	// }


}
